<template>
  <div>
    <el-drawer
      v-loading="loading"
      :wrapper-closable="false"
      append-to-body
      :title="title"
      :close-on-press-escape="true"
      size="80%"
      :modal="true"
      :visible.sync="isVisible"
      direction="rtl"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
      custom-class="production-order-drawer"
      :destroy-on-close="false"
      @close="close"
    >
      <div class="drawer-content">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <span class="order-title">{{ productionOrderData.name || '新建' }}</span>
            <el-tag effect="dark" size="mini" :color="getStateTagColor(productionOrderData.state)" style="color: white; border: none;">{{ getStateText(productionOrderData.state) }}</el-tag>
            <div v-if="productionOrderData.crm_order_no" class="order-info">
              <span class="info-item">关联订单编号: {{ productionOrderData.crm_order_no }}</span>
              <span>订单名称: {{ order_name }}</span>
            </div>
            <div v-if="productionOrderData.token" class="order-info" style="margin-top: 5px;">
              <span class="info-item" style="color: #67C23A;">Token: {{ productionOrderData.token }}</span>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="action-buttons">
            <el-button type="primary" round size="mini" :loading="saveLoading" @click="handleSaveProductionOrder">保存信息</el-button>
            <el-button v-if="allProductionOrders.length > 1" type="info" round size="mini" @click="showVersionsDialog">其他版本({{ allProductionOrders.length }})</el-button>
            <el-button v-if="productionOrderData.token" type="success" round size="mini" @click="openExternalLink">查看</el-button>
            <el-dropdown style="margin-left: 10px;" @command="handleOrderCommand">
              <el-button type="primary" round size="mini">
                生产单操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="copy">复制当前</el-dropdown-item>
                <el-dropdown-item command="new">新建</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button v-if="productionOrderData.id" round size="mini" type="primary" :disabled="loading" @click="handleAddCategory">添加类别</el-button>
            <el-button v-if="productionOrderData.id && hasConfirmableParams" round size="mini" type="warning" :disabled="loading" @click="handleResetAllConfirmations">全部设置为未确认</el-button>
          </el-col>
        </el-row>
        <el-divider>生产单信息</el-divider>
        <!-- 生产单基本信息 -->
        <el-form :model="productionOrderData" label-position="right" label-width="120px" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="文件名称" prop="name">
                <el-input v-model="productionOrderData.name" placeholder="请输入名称" @change="saveToCookies" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文件类型" prop="state">
                <el-select v-model="productionOrderData.state" placeholder="请选择类型" style="width: 100%" @change="saveToCookies">
                  <el-option label="询价单&供应商确认" value="1" />
                  <el-option label="样品生产单" value="2" />
                  <el-option label="大货生产单" value="3" />
                  <el-option label="PI文件" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联销售订单" prop="crm_order_no">
                <el-input v-model="productionOrderData.crm_order_no" placeholder="请输入关联销售订单编号" @change="saveToCookies" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contact_name">
                <el-input v-model="productionOrderData.contact_name" placeholder="输入采购人姓名" @change="saveToCookies" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contact_phone">
                <el-input v-model="productionOrderData.contact_phone" placeholder="输入采购人员电话" @change="saveToCookies" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- PI收款账号信息 - 只有当文件类型为PI时才显示 -->
        <template v-if="productionOrderData.state === '4'">
          <el-divider>PI收款账号信息</el-divider>
          <el-collapse v-model="piInfoCollapse">
            <el-collapse-item title="PI收款账号信息" name="pi_info">
              <template slot="title">
                <span>PI收款账号信息</span>
                <el-button type="primary" size="mini" style="margin-left: 10px;" @click.stop="showSelectPIAccount">
                  <i class="el-icon-plus" /> 选择PI账户
                </el-button>
                <el-button type="info" size="mini" style="margin-left: 5px;" @click.stop="showManagePIAccount">
                  <i class="el-icon-setting" /> 管理账户
                </el-button>
              </template>
              <el-form :model="productionOrderData" label-position="right" label-width="120px">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="货币" prop="currency">
                      <el-select v-model="productionOrderData.currency" placeholder="请选择货币" style="width: 100%" filterable>
                        <el-option v-for="currency in currencyOptions" :key="currency.value" :label="currency.label" :value="currency.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="订单金额" prop="order_amount">
                      <el-input v-model="productionOrderData.order_amount" placeholder="请输入订单金额(支持文字输入)" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="发票号" prop="invoice_number">
                      <el-input v-model="productionOrderData.invoice_number" placeholder="请输入发票号" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="公司名称" prop="pi_company_name">
                      <el-input v-model="productionOrderData.pi_company_name" placeholder="请输入公司名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="邮箱" prop="pi_email">
                      <el-input v-model="productionOrderData.pi_email" placeholder="请输入邮箱" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="电话" prop="pi_phone">
                      <el-input v-model="productionOrderData.pi_phone" placeholder="请输入电话" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="网站" prop="pi_website">
                      <el-input v-model="productionOrderData.pi_website" placeholder="请输入网站地址" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item label="公司Logo" prop="company_logo">
                      <div class="logo-input-container">
                        <el-input v-model="productionOrderData.company_logo" placeholder="请输入公司Logo图片URL" style="margin-bottom: 10px;" />
                        <div v-if="productionOrderData.company_logo" class="logo-preview">
                          <img :src="productionOrderData.company_logo" alt="公司Logo" class="logo-image" @error="handleLogoError" @click="previewLogo">
                          <el-button type="text" size="mini" class="clear-logo-btn" @click="clearLogo">
                            <i class="el-icon-delete" /> 清除
                          </el-button>
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="网站" prop="pi_website">
                      <el-input v-model="productionOrderData.pi_website" placeholder="请输入网站地址" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="PI地址" prop="pi_address">
                  <el-input v-model="productionOrderData.pi_address" type="textarea" :rows="3" placeholder="请输入PI地址" />
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="账户持有人" prop="pi_account_holder_name">
                      <el-input v-model="productionOrderData.pi_account_holder_name" placeholder="请输入账户持有人姓名" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="账户号码" prop="pi_account_number">
                      <el-input v-model="productionOrderData.pi_account_number" placeholder="请输入账户号码" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="银行名称" prop="pi_bank_name">
                  <el-input v-model="productionOrderData.pi_bank_name" placeholder="请输入银行名称" />
                </el-form-item>
                <el-form-item label="银行地址" prop="pi_bak_address">
                  <el-input v-model="productionOrderData.pi_bak_address" type="textarea" :rows="3" placeholder="请输入银行地址" />
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="ACH路由号" prop="pi_ach_routing_number">
                      <el-input v-model="productionOrderData.pi_ach_routing_number" placeholder="请输入ACH路由号码" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="电汇号码" prop="pi_wire_transfer_number">
                      <el-input v-model="productionOrderData.pi_wire_transfer_number" placeholder="请输入电汇号码" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="SWIFT代码" prop="pi_swift_code">
                      <el-input v-model="productionOrderData.pi_swift_code" placeholder="请输入SWIFT代码" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </template>

        <el-divider>参数信息</el-divider>
        <!-- 类别和参数区域 -->
        <div v-if="productionOrderData.categories && productionOrderData.categories.length > 0">
          <el-collapse v-model="activeCollapse">
            <draggable
              v-model="productionOrderData.categories"
              handle=".category-drag-handle"
              animation="300"
              @end="handleCategoryReorder"
            >
              <el-collapse-item
                v-for="(category, cIndex) in productionOrderData.categories"
                :key="category.id || category.tempId"
                :title="category.name || '未命名类别'"
                :name="category.id || category.tempId"
              >
                <template slot="title">
                  <span class="category-drag-handle"><i class="el-icon-d-caret" /></span>
                  <span>{{ category.name || '未命名类别' }}</span>
                  <span class="category-position">(排序: {{ category.position || cIndex + 1 }})</span>
                  <el-tag v-if="category.is_shown === false" type="danger" size="mini" style="margin-left: 5px;">已隐藏</el-tag>
                </template>
                <div class="category-container" style="margin-bottom: 15px">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <div class="form-item">
                        <el-autocomplete
                          v-model="category.name"
                          class="inline-input"
                          clearable
                          :fetch-suggestions="querySearchCategory"
                          placeholder="请输入类别名称"
                          style="width: 100%"
                          @select="handleSelectCategory"
                        />
                      </div>
                    </el-col>
                    <el-col :span="16">
                      <el-button type="primary" size="mini" @click="handleAddParameter(category)">添加参数</el-button>
                      <el-button v-if="productionOrderData.id" type="success" size="mini" :loading="categoryLoading" @click="handleSaveCategory(category)">保存类别</el-button>
                      <el-button type="danger" size="mini" @click="handleDeleteCategory(category, cIndex)">删除类别</el-button>
                      <el-switch
                        v-model="category.is_shown"
                        active-text="显示"
                        inactive-text="隐藏"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        style="margin-left: 10px;"
                        @change="handleCategoryVisibilityChange(category)"
                      />
                    </el-col>
                  </el-row>

                  <!-- 类别图片上传区域 -->
                  <div style="margin-bottom: 15px">
                    <span>类别图片：</span>
                    <div class="upload-container">
                      <!-- 粘贴上传区域 -->
                      <div v-loading="category.imageLoading" class="paste-area" tabindex="0" @paste="handlePaste($event, category)" @click="focusPasteArea($event)" @dragover.prevent @drop="handleDrop($event, category)">
                        <div v-if="!category.images || !category.images.length" class="paste-tip">
                          <i class="el-icon-picture-outline" />
                          <div>选择本框，直接粘贴图片</div>
                        </div>
                        <div v-else class="paste-images">
                          <div v-for="(img, index) in category.images" :key="index" class="image-item">
                            <img :src="img" class="preview-image" @click.stop="previewImage(img)">
                            <i class="el-icon-delete delete-icon" @click.stop="removeCategoryImage(category, index)" />
                            <div class="image-ai-button">
                              <AITask
                                show_name="提取要点"
                                task-name="task_productionimage_info"
                                :params="{image_url: img}"
                                button-text="AI分析"
                                button-type="primary"
                                size="mini"
                                button-icon="el-icon-s-opportunity"
                                dialog-title="图片内容分析"
                                :show-icon="true"
                                title="AI分析图片"
                                @apply="(result) => handleApplyAIResult(result, category)"
                              />
                            </div>
                          </div>
                        </div>
                      </div>

                      <input
                        :ref="`fileInput_${category.id || category.tempId}`"
                        type="file"
                        style="display: none"
                        accept="image/*"
                        multiple
                        @change="handleFileChange($event, category)"
                      >
                    </div>
                    <el-dialog :visible.sync="dialogImageVisible" append-to-body>
                      <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                  </div>

                  <!-- 参数列表 -->
                  <el-table :data="category.parameters || []" border style="width: 100%" class="parameters-table">
                    <el-table-column prop="name" label="参数名称" width="180">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.name" placeholder="参数名称" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" label="参数值">
                      <template slot-scope="scope">
                        <div class="markdown-input-container">
                          <div v-if="scope.row.value && isMarkdown(scope.row.value)" class="markdown-preview-container">
                            <v-md-editor v-model="scope.row.value" mode="preview" height="120px" />
                            <i class="el-icon-edit-outline markdown-icon" title="Markdown编辑器" @click="openMarkdownEditor(scope.row)" />
                          </div>
                          <template v-else>
                            <el-input
                              v-model="scope.row.value"
                              type="textarea"
                              :rows="3"
                              placeholder="支持多行输入，可用markdown语法"
                              clearable
                            />
                            <i class="el-icon-edit-outline markdown-icon" title="Markdown编辑器" @click="openMarkdownEditor(scope.row)" />
                          </template>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="color" label="文字颜色" width="180">
                      <template slot-scope="scope">
                        <el-color-picker v-model="scope.row.color" />
                      </template>
                    </el-table-column>
                    <el-table-column label="配置信息" width="320">
                      <template slot-scope="scope">
                        <div style="display: flex; flex-direction: column; gap: 8px;">
                          <div style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 12px; color: #606266; width: 70px;">颜色:</span>
                            <el-color-picker v-model="scope.row.color" size="mini" />
                          </div>
                          <div style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 12px; color: #606266; width: 70px;">数量:</span>
                            <el-input v-model="scope.row.unit" placeholder="数量单位" size="mini" style="flex: 1;" />
                          </div>
                          <div style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 12px; color: #606266; width: 70px;">价格:</span>
                            <el-input v-model="scope.row.price" placeholder="0.00" size="mini" style="flex: 1;" type="number" step="0.01" />
                          </div>
                          <div style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 12px; color: #606266; width: 70px;">需要确认:</span>
                            <el-switch v-model="scope.row.need_confirm" size="mini" />
                          </div>
                          <div v-if="scope.row.need_confirm && scope.row.id" style="display: flex; align-items: center; gap: 8px; margin-top: 8px;">
                            <span style="font-size: 12px; color: #606266; width: 70px;">确认状态:</span>
                            <el-tag :type="scope.row.confirm_status === 'confirmed' ? 'success' : 'info'" size="mini" style="flex: 1;">
                              {{ scope.row.confirm_status === 'confirmed' ? '已确认' : '未确认' }}
                            </el-tag>
                            <el-button
                              v-if="scope.row.confirm_status === 'confirmed'"
                              type="warning"
                              size="mini"
                              @click="handleToggleConfirmStatus(scope.row, 'pending')"
                            >
                              设为未确认
                            </el-button>
                            <el-button
                              v-else
                              type="success"
                              size="mini"
                              @click="handleToggleConfirmStatus(scope.row, 'confirmed')"
                            >
                              设为已确认
                            </el-button>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="图片" width="300">
                      <template slot-scope="scope">
                        <!-- 粘贴上传区域 -->
                        <div v-loading="scope.row.imageLoading" class="paste-area parameter-paste-area" tabindex="0" @paste="handleParameterPaste($event, scope.row)" @click="focusPasteArea($event)" @dragover.prevent @drop="handleParameterDrop($event, scope.row)">
                          <div v-if="!scope.row.images || !scope.row.images.length" class="paste-tip">
                            <i class="el-icon-picture-outline" />
                            <div>粘贴或拖拽图片</div>
                          </div>
                          <div v-else class="paste-images parameter-images">
                            <div v-for="(img, index) in scope.row.images" :key="index" class="parameter-image-item">
                              <img :src="img" class="preview-image" @click.stop="previewImage(img)">
                              <i class="el-icon-delete delete-icon" @click.stop="removeParameterImage(scope.row, index)" />
                              <div class="image-ai-button">
                                <AITask
                                  show_name="提取要点"
                                  task-name="task_productionimage_info"
                                  :params="{image_url: img}"
                                  button-text="AI分析"
                                  button-type="primary"
                                  size="mini"
                                  button-icon="el-icon-s-opportunity"
                                  dialog-title="图片内容分析"
                                  :show-icon="true"
                                  title="AI分析图片"
                                  @apply="(result) => handleApplyParameterAIResult(result, scope.row)"
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                        <input
                          :ref="`paramFileInput_${scope.row.id || scope.$index}`"
                          type="file"
                          style="display: none"
                          accept="image/*"
                          multiple
                          @change="handleParameterFileChange($event, scope.row)"
                        >
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                      <template slot-scope="scope">
                        <el-button v-if="productionOrderData.id" type="success" size="mini" :loading="parameterLoading" @click="handleSaveParameter(category, scope.row)">保存</el-button>
                        <el-button type="danger" size="mini" @click="handleDeleteParameter(category, scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <!-- 底部添加参数按钮 -->
                  <div class="bottom-add-button">
                    <el-button type="primary" size="mini" style="margin-top: 10px" @click="handleAddParameter(category)">
                      <i class="el-icon-plus" /> 添加参数
                    </el-button>
                  </div>
                </div>
              </el-collapse-item>
            </draggable>
          </el-collapse>
          <!-- 底部添加类别按钮 -->
          <div class="bottom-add-category">
            <el-button type="primary" style="margin-top: 15px" @click="handleAddCategory">
              <i class="el-icon-plus" /> 添加类别
            </el-button>
          </div>
        </div>
        <div v-else style="text-align: center; margin-top: 30px; padding: 40px 20px;">
          <div style="color: #909399; font-size: 14px; margin-bottom: 20px;">
            <i class="el-icon-box" style="font-size: 64px; display: block; margin-bottom: 20px; color: #c0c4cc;" />
            <span>暂无类别信息</span>
          </div>
          <el-button type="primary" @click="handleAddCategory">添加类别</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogImageVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!-- Markdown编辑对话框 -->
    <el-dialog
      title="Markdown编辑器"
      :visible.sync="markdownDialogVisible"
      width="80%"
      :before-close="closeMarkdownDialog"
      append-to-body
      custom-class="markdown-dialog"
    >
      <v-md-editor
        v-model="currentMarkdownContent"
        height="450px"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeMarkdownDialog">取消</el-button>
        <el-button type="primary" @click="confirmMarkdownEdit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 生产单版本对话框 -->
    <el-dialog
      :title="versionDialogTitle"
      :visible.sync="versionsDialogVisible"
      width="80%"
      append-to-body
    >
      <div style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="versionSearchKeyword"
              placeholder="搜索生产单名称"
              clearable
              prefix-icon="el-icon-search"
              @clear="handleVersionSearch"
              @input="handleVersionSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="versionFilterState" placeholder="状态筛选" clearable style="width: 100%" @change="handleVersionSearch">
              <el-option label="询价单文件" value="1" />
              <el-option label="样品生产单文件" value="2" />
              <el-option label="大货生产单文件" value="3" />
              <el-option label="PI文件" value="4" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-radio-group v-model="versionSortOrder" @change="handleVersionSearch">
              <el-radio-button label="desc">最新优先</el-radio-button>
              <el-radio-button label="asc">最早优先</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
      </div>

      <el-table v-loading="versionsLoading" :data="filteredProductionOrders" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="生产单名称">
          <template slot-scope="scope">
            <span>{{ scope.row.name || '未命名生产单' }}</span>
            <el-tag v-if="scope.row.id === productionOrderData.id" size="mini" type="success" style="margin-left: 5px;">当前</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="token" label="Token" width="300">
          <template slot-scope="scope">
            <div v-if="scope.row.token">
              <a href="javascript:void(0);" class="token-link" @click="openVersionExternalLink(scope.row)">
                {{ scope.row.token }}
              </a>
              <div v-if="scope.row.token_generated_at" class="token-time">
                <i class="el-icon-time" /> {{ scope.row.token_generated_at }}
              </div>
            </div>
            <span v-else>未生成</span>
          </template>
        </el-table-column>
        <el-table-column label="文件类型" width="200">
          <template slot-scope="scope">
            <el-tag :color="getStateTagColor(scope.row.state)" style="color: white; border: none;">{{ getStateText(scope.row.state) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" :disabled="scope.row.id === productionOrderData.id" @click="switchToVersion(scope.row)">
              {{ token ? '切换到此版本' : '选择' }}
            </el-button>
            <el-button v-if="token" type="danger" size="mini" :disabled="allProductionOrders.length <= 1" @click="handleDeleteVersion(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- PI账户选择对话框 -->
    <crmpiaccountinfo
      :visible.sync="piSelectVisible"
      :select-mode="true"
      @select="handlePIAccountSelect"
      @close="piSelectVisible = false"
    />

    <!-- PI账户管理对话框 -->
    <crmpiaccountinfo
      :visible.sync="piManageVisible"
      :select-mode="false"
      @close="piManageVisible = false"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete, ToggleConfirmStatus, ResetAllConfirmations } from '@/api/crm/crmproductionorder'
import { Post as PostCategory, Put as PutCategory, Delete as DeleteCategory, GetDefaultParams } from '@/api/crm/productionordercategory'
import { Post as PostParameter, Put as PutParameter, Delete as DeleteParameter } from '@/api/crm/pocparameter'
import { Get as GetOrders } from '@/api/crm/crmorder'
import { Post as UploadBase64Image } from '@/api/cms/image'
import qs from 'qs'
import Cookies from 'js-cookie'
import draggable from 'vuedraggable'
import AITask from '@/components/AITask'
import Crmpiaccountinfo from './crmpiaccountinfo'

export default {
  name: 'Crmproductionorder',
  components: { draggable, AITask, Crmpiaccountinfo },
  props: {
    order_no: {
      type: [Number, String],
      default: ''
    },
    order_name: {
      type: [Number, String],
      default: ''
    },
    token: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    uploadDirectory: {
      type: Number,
      default: -1
    },
    uploadKeyword: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: '生产单详情',
      productionOrderData: {
        name: '',
        state: '1', // 默认为询价单，使用数字值而不是文字
        crm_order_no: '',
        contact_phone: '',
        contact_name: '',
        categories: [],
        // PI相关字段
        currency: 'USD',
        order_amount: 'USD:100',
        invoice_number: '',
        pi_address: '',
        pi_email: '',
        pi_phone: '',
        pi_website: '',
        pi_account_holder_name: '',
        pi_account_number: '',
        pi_bank_name: '',
        pi_bak_address: '',
        pi_ach_routing_number: '',
        pi_wire_transfer_number: '',
        pi_swift_code: '',
        pi_company_name: '',
        company_logo: ''
      },
      categoryOptions: [
        { value: '需求要点' },
        { value: '版型图' },
        { value: '数量' },
        { value: '面料' },
        { value: 'logo' },
        { value: '辅料' },
        { value: '特殊要求' }
      ],
      // 50种主流货币列表
      currencyOptions: [
        { label: '美元 (USD)', value: 'USD' },
        { label: '人民币 (CNY)', value: 'CNY' },
        { label: '欧元 (EUR)', value: 'EUR' },
        { label: '英镑 (GBP)', value: 'GBP' },
        { label: '日元 (JPY)', value: 'JPY' },
        { label: '瑞士法郎 (CHF)', value: 'CHF' },
        { label: '加拿大元 (CAD)', value: 'CAD' },
        { label: '澳大利亚元 (AUD)', value: 'AUD' },
        { label: '新西兰元 (NZD)', value: 'NZD' },
        { label: '韩元 (KRW)', value: 'KRW' },
        { label: '新加坡元 (SGD)', value: 'SGD' },
        { label: '港币 (HKD)', value: 'HKD' },
        { label: '挪威克朗 (NOK)', value: 'NOK' },
        { label: '瑞典克朗 (SEK)', value: 'SEK' },
        { label: '丹麦克朗 (DKK)', value: 'DKK' },
        { label: '波兰兹罗提 (PLN)', value: 'PLN' },
        { label: '捷克克朗 (CZK)', value: 'CZK' },
        { label: '匈牙利福林 (HUF)', value: 'HUF' },
        { label: '俄罗斯卢布 (RUB)', value: 'RUB' },
        { label: '土耳其里拉 (TRY)', value: 'TRY' },
        { label: '南非兰特 (ZAR)', value: 'ZAR' },
        { label: '巴西雷亚尔 (BRL)', value: 'BRL' },
        { label: '墨西哥比索 (MXN)', value: 'MXN' },
        { label: '印度卢比 (INR)', value: 'INR' },
        { label: '泰铢 (THB)', value: 'THB' },
        { label: '马来西亚林吉特 (MYR)', value: 'MYR' },
        { label: '印度尼西亚盾 (IDR)', value: 'IDR' },
        { label: '菲律宾比索 (PHP)', value: 'PHP' },
        { label: '越南盾 (VND)', value: 'VND' },
        { label: '台币 (TWD)', value: 'TWD' },
        { label: '以色列新谢克尔 (ILS)', value: 'ILS' },
        { label: '沙特阿拉伯里亚尔 (SAR)', value: 'SAR' },
        { label: '阿联酋迪拉姆 (AED)', value: 'AED' },
        { label: '埃及镑 (EGP)', value: 'EGP' },
        { label: '卡塔尔里亚尔 (QAR)', value: 'QAR' },
        { label: '科威特第纳尔 (KWD)', value: 'KWD' },
        { label: '巴林第纳尔 (BHD)', value: 'BHD' },
        { label: '约旦第纳尔 (JOD)', value: 'JOD' },
        { label: '黎巴嫩镑 (LBP)', value: 'LBP' },
        { label: '摩洛哥迪拉姆 (MAD)', value: 'MAD' },
        { label: '突尼斯第纳尔 (TND)', value: 'TND' },
        { label: '阿尔及利亚第纳尔 (DZD)', value: 'DZD' },
        { label: '尼日利亚奈拉 (NGN)', value: 'NGN' },
        { label: '肯尼亚先令 (KES)', value: 'KES' },
        { label: '加纳塞地 (GHS)', value: 'GHS' },
        { label: '乌干达先令 (UGX)', value: 'UGX' },
        { label: '坦桑尼亚先令 (TZS)', value: 'TZS' },
        { label: '智利比索 (CLP)', value: 'CLP' },
        { label: '阿根廷比索 (ARS)', value: 'ARS' },
        { label: '哥伦比亚比索 (COP)', value: 'COP' }
      ],
      paramsOptions: [
        { value: '尺寸' },
        { value: '颜色' },
        { value: '成分' },
        { value: '克重' }
      ],
      loading: false,
      saveLoading: false,
      categoryLoading: false,
      parameterLoading: false,
      activeCollapse: [], // 当前展开的折叠面板
      dialogImageUrl: '',
      dialogImageVisible: false,
      stateoptions: ['询价&供应链确认', '生产单'],
      // 订单搜索相关
      orderOptions: [],
      ordersLoading: false,
      orderSearchKeyword: '',
      isVisible: false,
      // Markdown编辑相关
      markdownDialogVisible: false,
      currentMarkdownContent: '',
      currentEditingParameter: null,
      saveParamTimeout: null,
      allProductionOrders: [],
      versionsDialogVisible: false,
      versionsLoading: false,
      versionSearchKeyword: '',
      versionFilterState: '',
      versionSortOrder: 'desc',
      piInfoCollapse: [], // 修改为空数组，默认折叠PI收款账号信息
      piSelectVisible: false,
      piManageVisible: false
    }
  },
  computed: {
    // 动态对话框标题
    versionDialogTitle() {
      if (this.token) {
        return '生产单版本列表'
      } else {
        return '请选择要编辑的生产单'
      }
    },
    // 判断是否有需要确认的参数
    hasConfirmableParams() {
      if (!this.productionOrderData.categories || !this.productionOrderData.categories.length) {
        return false
      }
      return this.productionOrderData.categories.some(category => {
        return category.parameters && category.parameters.some(param => param.need_confirm)
      })
    },
    // 根据搜索关键词、状态筛选和排序规则过滤生产单
    filteredProductionOrders() {
      if (!this.allProductionOrders || !this.allProductionOrders.length) {
        return []
      }

      // 先进行筛选
      const result = this.allProductionOrders.filter(order => {
        // 名称是否包含关键字（忽略大小写）
        const nameMatch = !this.versionSearchKeyword ||
          (order.name && order.name.toLowerCase().includes(this.versionSearchKeyword.toLowerCase()))

        // 状态是否匹配
        const stateMatch = !this.versionFilterState || order.state === this.versionFilterState

        return nameMatch && stateMatch
      })

      // 再进行排序
      result.sort((a, b) => {
        const dateA = new Date(a.create_at)
        const dateB = new Date(b.create_at)

        return this.versionSortOrder === 'desc'
          ? dateB - dateA // 最新优先
          : dateA - dateB // 最早优先
      })

      return result
    }
  },
  watch: {
    order_no: {
      handler(val) {
        if (val) {
          this.productionOrderData.crm_order_no = val
          // 如果是新建生产单且没有名称，设置默认名称
          if (!this.productionOrderData.id && !this.productionOrderData.name) {
            this.productionOrderData.name = `${val}+生产需求单`
          }
        }

        console.log('order_no', val)
        if (val && this.isVisible) {
          this.getProductionOrderData()
        }
      },
      immediate: true
    },
    visible: {
      handler(val) {
        this.isVisible = val
        if (val) {
          // 立即显示loading状态
          this.loading = true

          // 延迟一点执行数据加载，让loading状态先显示出来
          setTimeout(() => {
            this.getProductionOrderData()
            // 抽屉显示时，延迟一下再刷新图片
            setTimeout(() => {
              this.refreshImages()
            }, 500)
          }, 100)
        }
      },
      immediate: true
    },
    // 监控联系人和联系电话的变化，保存到cookies
    'productionOrderData.contact_name': function(val) {
      this.saveToCookies()
    },
    'productionOrderData.contact_phone': function(val) {
      this.saveToCookies()
    },
    // 监控生产单状态变化，当为PI文件时自动展开PI收款账号信息
    'productionOrderData.state': function(newVal, oldVal) {
      if (newVal === '4') {
        // 当状态为PI文件时，自动展开PI收款账号信息
        if (!this.piInfoCollapse.includes('pi_info')) {
          this.piInfoCollapse = ['pi_info']
        }
      } else {
        // 当状态不是PI文件时，收起PI收款账号信息
        this.piInfoCollapse = []
      }
    }
  },
  created() {
    this.handleGetDefaultParams()
    if (this.order_no && this.isVisible) {
      this.getProductionOrderData()
    } else {
      // 如果没有order_no，尝试从cookies恢复用户数据
      this.restoreFromCookies()
    }
  },
  mounted() {
    // 初始化所有类别和参数的imageLoading状态为false
    if (this.productionOrderData && this.productionOrderData.categories) {
      this.productionOrderData.categories.forEach(category => {
        this.$set(category, 'imageLoading', false)

        if (category.parameters) {
          category.parameters.forEach(param => {
            this.$set(param, 'imageLoading', false)
          })
        }
      })
    }

    // 组件挂载后尝试从cookies中恢复数据
    this.restoreFromCookies()
  },
  // 在组件销毁前清理定时器
  beforeDestroy() {
    // 清理任何可能存在的定时器
    if (this.saveParamTimeout) {
      clearTimeout(this.saveParamTimeout)
    }
  },
  methods: {
    // 保存用户输入到cookies
    saveToCookies() {
      // 创建一个对象存储需要保存的字段
      const cookieData = {
        contact_name: this.productionOrderData.contact_name,
        contact_phone: this.productionOrderData.contact_phone,
        name: this.productionOrderData.name,
        state: this.productionOrderData.state,
        // PI相关字段
        currency: this.productionOrderData.currency,
        order_amount: this.productionOrderData.order_amount,
        invoice_number: this.productionOrderData.invoice_number,
        pi_address: this.productionOrderData.pi_address,
        pi_email: this.productionOrderData.pi_email,
        pi_phone: this.productionOrderData.pi_phone,
        pi_website: this.productionOrderData.pi_website,
        pi_account_holder_name: this.productionOrderData.pi_account_holder_name,
        pi_account_number: this.productionOrderData.pi_account_number,
        pi_bank_name: this.productionOrderData.pi_bank_name,
        pi_bak_address: this.productionOrderData.pi_bak_address,
        pi_ach_routing_number: this.productionOrderData.pi_ach_routing_number,
        pi_wire_transfer_number: this.productionOrderData.pi_wire_transfer_number,
        pi_swift_code: this.productionOrderData.pi_swift_code,
        pi_company_name: this.productionOrderData.pi_company_name,
        company_logo: this.productionOrderData.company_logo
      }

      // 转换为JSON字符串并保存到cookies，设置有效期为30天
      Cookies.set('production_order_user_data', JSON.stringify(cookieData), { expires: 30 })
      console.log('已保存用户数据到cookies:', cookieData)
    },

    // 从cookies恢复用户输入
    restoreFromCookies() {
      try {
        const cookieData = Cookies.get('production_order_user_data')
        if (cookieData) {
          const userData = JSON.parse(cookieData)
          console.log('从cookies恢复用户数据:', userData)

          // 只有在创建新的生产单时才应用cookie中的数据
          if (!this.productionOrderData.id) {
            // 恢复联系人和联系电话
            if (userData.contact_name) {
              this.productionOrderData.contact_name = userData.contact_name
            }

            if (userData.contact_phone) {
              this.productionOrderData.contact_phone = userData.contact_phone
            }

            // 如果是新建生产单且没有名称，则设置默认名称或恢复cookie中的名称
            if (!this.productionOrderData.name) {
              if (userData.name) {
                this.productionOrderData.name = userData.name
              } else if (this.order_no) {
                // 如果没有cookie数据且有订单编号，设置默认名称
                this.productionOrderData.name = `${this.order_no}+生产需求单`
              }
            }

            // 如果状态为默认值，则恢复状态
            if (userData.state && (!this.productionOrderData.state || this.productionOrderData.state === '1')) {
              this.productionOrderData.state = userData.state
            }

            // 恢复PI相关字段
            const piFields = [
              'currency', 'order_amount', 'invoice_number', 'pi_address', 'pi_email', 'pi_phone', 'pi_website',
              'pi_account_holder_name', 'pi_account_number', 'pi_bank_name', 'pi_bak_address',
              'pi_ach_routing_number', 'pi_wire_transfer_number', 'pi_swift_code', 'pi_company_name', 'company_logo'
            ]

            piFields.forEach(field => {
              if (userData[field] !== undefined && userData[field] !== '') {
                this.productionOrderData[field] = userData[field]
              }
            })
          }
        } else {
          // 如果没有cookie数据，但有订单编号且当前名称为空，设置默认名称
          if (!this.productionOrderData.id && !this.productionOrderData.name && this.order_no) {
            this.productionOrderData.name = `${this.order_no}+生产需求单`
          }
        }
      } catch (error) {
        console.error('恢复用户数据失败:', error)
        // 如果恢复失败，但有订单编号且当前名称为空，设置默认名称
        if (!this.productionOrderData.id && !this.productionOrderData.name && this.order_no) {
          this.productionOrderData.name = `${this.order_no}+生产需求单`
        }
      }
    },

    // 获取生产单数据
    getProductionOrderData() {
      if (!this.order_no) {
        console.log('没有订单编号，跳过获取生产单数据')
        // 当没有订单数据时，是新建状态，此时尝试从cookies恢复用户数据
        this.restoreFromCookies()
        this.loading = false
        return
      }

      this.loading = true
      console.log('获取生产单数据，订单编号:', this.order_no, 'token:', this.token)

      // 构建查询参数
      const queryParams = { order_no: this.order_no }
      if (this.token) {
        queryParams.token = this.token
      }

      Get(null, qs.stringify(queryParams)).then(response => {
        console.log('获取到生产单数据:', response.data)

        if (response.data && response.data.data && response.data.data.length > 0) {
          // 保存所有相关生产单数据用于版本切换
          this.allProductionOrders = [...response.data.data]

          // 按创建时间降序排序，确保最新的在前面
          this.allProductionOrders.sort((a, b) => {
            return new Date(b.create_at) - new Date(a.create_at)
          })

          // 如果提供了token，优先找到对应token的生产单
          let targetProductionOrder
          if (this.token) {
            targetProductionOrder = this.allProductionOrders.find(po => po.token === this.token)
            if (targetProductionOrder) {
              console.log('找到token对应的生产单:', targetProductionOrder)
            } else {
              console.warn('未找到token对应的生产单，使用最新的')
              targetProductionOrder = this.allProductionOrders[0]
            }
          } else {
            // 如果没有token且有多个生产单，弹出选择对话框
            if (this.allProductionOrders.length > 1) {
              console.log('没有token且有多个生产单，弹出选择对话框')
              this.loading = false
              this.versionsDialogVisible = true
              return
            }
            // 如果只有一个生产单，直接使用
            targetProductionOrder = this.allProductionOrders[0]
          }

          // 临时存储数据，使用深拷贝避免引用问题
          const tempData = JSON.parse(JSON.stringify(targetProductionOrder))
          this.title = `生产单详情: ${tempData.name || '未命名'}`

          console.log('处理后的生产单数据:', tempData)

          // 确保categories存在且是数组
          if (!tempData.categories) {
            tempData.categories = []
          }

          // 处理类别和参数中的图片字符串，将其转换为数组
          tempData.categories.forEach(category => {
            // 处理类别图片
            if (category.images && typeof category.images === 'string') {
              category.images = category.images.split(',').filter(url => url.trim() !== '')
            } else if (!category.images) {
              category.images = []
            }

            // 处理参数图片
            if (category.parameters && Array.isArray(category.parameters)) {
              category.parameters.forEach(param => {
                if (param.images && typeof param.images === 'string') {
                  param.images = param.images.split(',').filter(url => url.trim() !== '')
                } else if (!param.images) {
                  param.images = []
                }
              })
            }
          })

          // 完全替换数据，触发响应式更新
          this.productionOrderData = tempData

          // 使用$nextTick确保DOM已更新
          this.$nextTick(() => {
            // 设置初始展开的面板
            this.activeCollapse = tempData.categories.map(cat => cat.id || cat.tempId)

            // 检查状态，如果是PI文件状态，自动展开PI收款账号信息
            if (tempData.state === '4') {
              this.piInfoCollapse = ['pi_info']
              console.log('检测到PI文件状态，自动展开PI收款账号信息')
            }

            // 刷新图片显示
            this.refreshImages()
          })

          // 延迟一点关闭loading状态，避免闪烁
          setTimeout(() => {
            this.loading = false
          }, 300)
        } else {
          console.log('没有找到匹配的生产单数据，创建新的生产单')
          this.productionOrderData = {
            name: this.order_no ? `${this.order_no}+生产需求单` : '',
            state: '1',
            crm_order_no: this.order_no,
            categories: [],
            // PI相关字段
            currency: 'USD',
            order_amount: 'USD:100',
            invoice_number: '',
            pi_address: '',
            pi_email: '',
            pi_phone: '',
            pi_website: '',
            pi_account_holder_name: '',
            pi_account_number: '',
            pi_bank_name: '',
            pi_bak_address: '',
            pi_ach_routing_number: '',
            pi_wire_transfer_number: '',
            pi_swift_code: '',
            pi_company_name: '',
            company_logo: ''
          }
          this.title = '新建生产单'
          // 尝试从cookies恢复用户数据
          this.restoreFromCookies()
          this.loading = false
        }
      }).catch(error => {
        console.error('获取生产单数据失败', error)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '获取生产单数据失败: ' + (error.message || '未知错误')
        })

        // 创建一个新的空生产单对象
        this.productionOrderData = {
          name: this.order_no ? `${this.order_no}+生产需求单` : '',
          state: '1',
          crm_order_no: this.order_no,
          categories: [],
          // PI相关字段
          currency: 'USD',
          order_amount: 'USD:100',
          invoice_number: '',
          pi_address: '',
          pi_email: '',
          pi_phone: '',
          pi_website: '',
          pi_account_holder_name: '',
          pi_account_number: '',
          pi_bank_name: '',
          pi_bak_address: '',
          pi_ach_routing_number: '',
          pi_wire_transfer_number: '',
          pi_swift_code: '',
          pi_company_name: '',
          company_logo: ''
        }
        // 尝试从cookies恢复用户数据
        this.restoreFromCookies()
        this.title = '新建生产单'
      })
    },

    // 保存生产单
    handleSaveProductionOrder() {
      this.loading = true
      this.saveLoading = true

      // 构建要保存的数据对象
      const saveData = { ...this.productionOrderData }

      // 确定是更新还是新建
      const isUpdate = !!saveData.id

      const saveOrUpdateProductionOrder = () => {
        if (isUpdate) {
          // 更新现有生产单
          return Put(saveData.id, saveData)
        } else {
          // 创建新生产单
          return Post(saveData)
        }
      }

      saveOrUpdateProductionOrder()
        .then(response => {
          const savedProductionOrder = response.data.data
          console.log('生产单保存/更新成功:', savedProductionOrder)

          // 如果是新创建的，更新ID
          if (!isUpdate) {
            this.productionOrderData.id = savedProductionOrder.id
          }
        })
        .then(() => {
          console.log('所有类别和参数保存完成，准备重新获取最新数据')

          // 先显示成功提示
          this.$notify({
            title: '成功',
            message: '生产单保存成功',
            type: 'success',
            duration: 2000
          })

          // 重新获取完整数据
          if (this.productionOrderData.id) {
            this.reloadProductionOrderData(this.productionOrderData.id)
          } else {
            // 如果没有ID，通过订单号刷新数据
            this.getProductionOrderData()
          }

          this.saveLoading = false
        })
        .catch(error => {
          console.error('保存生产单失败', error)
          this.loading = false
          this.saveLoading = false
          this.$notify.error({
            title: '错误',
            message: '保存生产单失败: ' + (error.message || '未知错误')
          })
        })
    },

    // 根据ID重新加载生产单数据
    reloadProductionOrderData(id) {
      console.log('根据ID重新加载生产单数据:', id)
      this.loading = true

      Get(id).then(response => {
        console.log('重新获取到生产单数据:', response.data)

        if (response.data) {
          // 临时存储数据，不直接替换
          const tempData = JSON.parse(JSON.stringify(response.data))

          // 确保categories存在且是数组
          if (!tempData.categories) {
            tempData.categories = []
          }

          // 处理类别和参数中的图片字符串，将其转换为数组
          tempData.categories.forEach(category => {
            // 处理类别图片
            if (category.images && typeof category.images === 'string') {
              category.images = category.images.split(',').filter(url => url.trim() !== '')
            } else if (!category.images) {
              category.images = []
            }

            // 处理参数图片
            if (category.parameters && Array.isArray(category.parameters)) {
              category.parameters.forEach(param => {
                if (param.images && typeof param.images === 'string') {
                  param.images = param.images.split(',').filter(url => url.trim() !== '')
                } else if (!param.images) {
                  param.images = []
                }
              })
            }
          })

          // 更新标题
          this.title = `生产单详情: ${tempData.name || '未命名'}`

          // 完全替换数据，强制刷新
          this.productionOrderData = tempData

          // 使用$nextTick确保DOM已更新
          this.$nextTick(() => {
            // 设置初始展开的面板
            this.activeCollapse = this.productionOrderData.categories.map(cat => cat.id || cat.tempId)
            console.log('数据加载完成，类别数:', this.productionOrderData.categories.length)

            // 检查状态，如果是PI文件状态，自动展开PI收款账号信息
            if (this.productionOrderData.state === '4') {
              this.piInfoCollapse = ['pi_info']
              console.log('检测到PI文件状态，自动展开PI收款账号信息')
            }

            // 强制刷新图片显示
            this.refreshImages()
          })

          // 延迟一点关闭loading状态，避免闪烁
          setTimeout(() => {
            this.loading = false
          }, 300)
        } else {
          this.loading = false
        }
      }).catch(error => {
        console.error('重新加载生产单数据失败', error)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '重新加载数据失败: ' + (error.message || '未知错误')
        })
      })
    },

    // 刷新图片显示
    refreshImages() {
      this.$nextTick(() => {
        // 强制浏览器重新加载图片
        const images = document.querySelectorAll('.preview-image')
        images.forEach(img => {
          const originalSrc = img.src
          if (originalSrc) {
            // 添加时间戳强制刷新缓存
            img.src = originalSrc.includes('?')
              ? originalSrc + '&_t=' + new Date().getTime()
              : originalSrc + '?_t=' + new Date().getTime()
          }
        })
        console.log('已刷新', images.length, '张图片')
      })
    },

    // 保存所有类别及其参数
    saveCategories(productionOrderId) {
      console.log('保存类别，生产单ID:', productionOrderId)
      if (!productionOrderId) {
        console.error('保存类别失败：缺少生产单ID')
        return Promise.reject(new Error('缺少生产单ID'))
      }

      const promises = []

      for (const category of this.productionOrderData.categories || []) {
        // 确保图片数组存在并且是字符串格式
        const images = category.images || []
        console.log(`处理类别[${category.name}]的图片:`, images)

        // 构建要保存的类别数据
        const categoryData = {
          name: category.name,
          production_order: productionOrderId,
          images: images.join(',') // 将图片URL数组转换为逗号分隔的字符串
        }

        console.log('保存类别数据:', categoryData)

        let categoryPromise

        if (category.id) {
          // 更新现有类别
          console.log(`更新已有类别[ID:${category.id}]`)
          categoryPromise = PutCategory(category.id, categoryData)
            .then(response => {
              console.log(`类别[ID:${category.id}]更新成功:`, response.data)
              const savedCategory = response.data
              return this.saveParameters(category.parameters || [], savedCategory.id)
            })
            .catch(error => {
              console.error(`更新类别[ID:${category.id}]失败:`, error)
              return Promise.reject(error)
            })
        } else {
          // 创建新类别
          console.log('创建新类别:', category.name)
          categoryPromise = PostCategory(categoryData)
            .then(response => {
              console.log('新类别创建成功:', response.data)
              const savedCategory = response.data
              category.id = savedCategory.id // 更新内存中的ID
              return this.saveParameters(category.parameters || [], savedCategory.id)
            })
            .catch(error => {
              console.error('创建新类别失败:', error)
              return Promise.reject(error)
            })
        }

        promises.push(categoryPromise)
      }

      return Promise.all(promises)
    },

    // 保存指定类别的所有参数
    saveParameters(parameters, categoryId) {
      console.log(`保存参数，类别ID:${categoryId}，参数数量:${parameters.length}`)
      if (!categoryId) {
        console.error('保存参数失败：缺少类别ID')
        return Promise.reject(new Error('缺少类别ID'))
      }

      // 过滤掉名称为空的参数
      const validParameters = parameters.filter(param => param.name && param.name.trim() !== '')

      if (validParameters.length < parameters.length) {
        console.log(`过滤掉 ${parameters.length - validParameters.length} 个空名称参数`)
      }

      const promises = []

      for (const param of validParameters) {
        // 确保图片数组存在并且是字符串格式
        const images = param.images || []
        console.log(`处理参数[${param.name}]的图片:`, images)

        // 构建要保存的参数数据
        const paramData = {
          name: param.name,
          value: param.value,
          color: param.color || '#000000',
          unit: param.unit || '',
          price: param.price || 0.0,
          crmproduction_order_category: categoryId,
          images: images.join(','), // 将图片URL数组转换为逗号分隔的字符串
          need_confirm: param.need_confirm !== undefined ? param.need_confirm : true, // 是否需要确认，默认需要确认
          confirm_status: param.confirm_status || 'pending' // 确认状态
        }

        console.log('保存参数数据:', paramData)

        let paramPromise

        if (param.id) {
          // 更新现有参数
          console.log(`更新已有参数[ID:${param.id}]`)
          paramPromise = PutParameter(param.id, paramData)
            .then(response => {
              console.log(`参数[ID:${param.id}]更新成功:`, response.data)
              return response
            })
            .catch(error => {
              console.error(`更新参数[ID:${param.id}]失败:`, error)
              return Promise.reject(error)
            })
        } else {
          // 创建新参数
          console.log('创建新参数:', param.name)
          paramPromise = PostParameter(paramData)
            .then(response => {
              console.log('新参数创建成功:', response.data)
              param.id = response.data.id // 更新内存中的ID
              return response
            })
            .catch(error => {
              console.error('创建新参数失败:', error)
              return Promise.reject(error)
            })
        }

        promises.push(paramPromise)
      }

      return Promise.all(promises)
    },

    // 添加新类别
    handleAddCategory() {
      if (!this.productionOrderData.categories) {
        this.productionOrderData.categories = []
      }

      // 计算最大position值
      let maxPosition = 0
      if (this.productionOrderData.categories.length > 0) {
        maxPosition = Math.max(...this.productionOrderData.categories.map(cat => cat.position || 0))
      }

      const newCategory = {
        name: '新类别',
        tempId: 'new-cat-' + Date.now(), // 临时ID用于界面展示
        production_order: this.productionOrderData.id,
        parameters: [],
        images: [],
        position: maxPosition + 1, // 设置为当前最大position + 1
        is_shown: true // 默认为显示
      }

      this.productionOrderData.categories.push(newCategory)

      // 确保新类别被展开 - 使用$nextTick确保DOM已更新
      this.$nextTick(() => {
        // 保留当前展开项，同时添加新类别到展开列表
        if (!this.activeCollapse) {
          this.activeCollapse = []
        }
        this.activeCollapse = [...this.activeCollapse, newCategory.tempId]

        // 滚动到新添加的类别位置
        setTimeout(() => {
          const element = document.querySelector(`[name="${newCategory.tempId}"]`)
          if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'center' })
          }
        }, 100)
      })
    },

    // 全部重置确认状态
    handleResetAllConfirmations() {
      this.$confirm('确认将所有参数的确认状态重置为未确认吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在重置...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        ResetAllConfirmations(this.productionOrderData.id).then(response => {
          loading.close()
          if (response.success) {
            this.$notify({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            // 重新加载数据以更新UI
            this.getProductionOrderData()
          } else {
            this.$notify.error({
              title: '错误',
              message: response.msg || '重置失败'
            })
          }
        }).catch(error => {
          loading.close()
          console.error('重置确认状态失败', error)
          this.$notify.error({
            title: '错误',
            message: '重置失败，请稍后重试'
          })
        })
      }).catch(() => {
        // 取消操作
      })
    },

    // 切换单个参数的确认状态
    handleToggleConfirmStatus(parameter, targetStatus) {
      const statusText = targetStatus === 'confirmed' ? '已确认' : '未确认'
      this.$confirm(`确认将此参数设置为${statusText}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在修改...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        ToggleConfirmStatus(parameter.id, targetStatus).then(response => {
          loading.close()
          if (response.success) {
            // 更新本地数据
            parameter.confirm_status = targetStatus
            this.$notify({
              title: '成功',
              message: `已设置为${statusText}`,
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: response.msg || '修改失败'
            })
          }
        }).catch(error => {
          loading.close()
          console.error('修改确认状态失败', error)
          this.$notify.error({
            title: '错误',
            message: '修改失败，请稍后重试'
          })
        })
      }).catch(() => {
        // 取消操作
      })
    },

    // 删除类别
    handleDeleteCategory(category, index) {
      this.$confirm('确认删除该类别?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (category.id) {
          // 已保存到数据库的类别，需要通过API删除
          this.categoryLoading = true
          DeleteCategory(category.id).then(() => {
            this.productionOrderData.categories.splice(index, 1)
            this.$notify({
              title: '成功',
              message: '类别删除成功',
              type: 'success'
            })
            this.categoryLoading = false
          }).catch(error => {
            console.error('删除类别失败', error)
            this.categoryLoading = false
            this.$notify.error({
              title: '错误',
              message: '删除类别失败'
            })
          })
        } else {
          // 未保存到数据库的类别，直接从内存中删除
          this.productionOrderData.categories.splice(index, 1)
        }
      }).catch(() => {
        // 取消删除
      })
    },

    // 添加参数
    handleAddParameter(category) {
      if (!category.parameters) {
        category.parameters = []
      }

      category.parameters.push({
        name: '',
        value: '',
        color: '#000000',
        unit: '',
        price: 0.0,
        crmproduction_order_category: category.id,
        images: [],
        need_confirm: true, // 默认需要确认
        confirm_status: 'pending' // 默认待确认状态
      })
    },

    // 删除参数
    handleDeleteParameter(category, paramIndex) {
      this.$confirm('确认删除该参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = category.parameters[paramIndex]

        if (param.id) {
          // 已保存到数据库的参数，需要通过API删除
          this.parameterLoading = true
          DeleteParameter(param.id).then(() => {
            category.parameters.splice(paramIndex, 1)
            this.$notify({
              title: '成功',
              message: '参数删除成功',
              type: 'success'
            })
            this.parameterLoading = false
          }).catch(error => {
            console.error('删除参数失败', error)
            this.parameterLoading = false
            this.$notify.error({
              title: '错误',
              message: '删除参数失败'
            })
          })
        } else {
          // 未保存到数据库的参数，直接从内存中删除
          category.parameters.splice(paramIndex, 1)
        }
      }).catch(() => {
        // 取消删除
      })
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    // 类别图片上传成功
    handleCategoryUploadSuccess(response, category) {
      if (!category.images) {
        category.images = []
      }
      category.images.push(response.url)
    },

    // 类别图片删除
    handleCategoryUploadRemove(file, category) {
      if (category.images) {
        const index = category.images.indexOf(file.url)
        if (index !== -1) {
          category.images.splice(index, 1)
        }
      }
    },

    // 参数图片上传成功
    handleParameterUploadSuccess(response, parameter) {
      if (!parameter.images) {
        parameter.images = []
      }
      parameter.images.push(response.url)
    },

    // 参数图片删除
    handleParameterUploadRemove(file, parameter) {
      if (parameter.images) {
        const index = parameter.images.indexOf(file.url)
        if (index !== -1) {
          parameter.images.splice(index, 1)
        }
      }
    },

    // 搜索订单
    searchOrders(query) {
      if (query.length < 2) return

      this.ordersLoading = true
      GetOrders(null, qs.stringify({
        kw: query,
        pagesize: 10,
        page: 1,
        project_id: this.$store.getters.projectId
      })).then(response => {
        this.orderOptions = response.data.data
        this.ordersLoading = false
      }).catch(error => {
        console.error('搜索订单失败', error)
        this.ordersLoading = false
      })
    },

    // 获取状态标签类型
    getStateTagType(state) {
      // 确保状态值是字符串
      const stateStr = String(state)

      // 映射数字ID到类型（保留用于不支持自定义颜色的地方）
      const stateMap = {
        '1': 'primary',
        '2': 'warning',
        '3': 'danger',
        '4': '',
        // 添加名称映射
        '询价单&供应商确认': 'primary',
        '询价单': 'primary',
        '样品生产单': 'warning',
        '样品生产': 'warning',
        '大货生产单': 'danger',
        '大货生产': 'danger',
        'PI文件': '',
        'PI': ''
      }

      // 尝试返回映射的值，如果不存在则返回空字符串（使用自定义颜色）
      return stateMap[stateStr] || ''
    },

    // 获取状态标签颜色
    getStateTagColor(state) {
      const stateStr = String(state)

      // 自定义颜色映射
      const colorMap = {
        '1': '#409EFF', // 询价单 - 蓝色
        '2': '#E6A23C', // 样品生产单 - 橙色
        '3': '#F56C6C', // 大货生产单 - 红色
        '4': '#9C27B0', // PI文件 - 紫色
        // 添加名称映射
        '询价单&供应商确认': '#409EFF',
        '询价单': '#409EFF',
        '样品生产单': '#E6A23C',
        '样品生产': '#E6A23C',
        '大货生产单': '#F56C6C',
        '大货生产': '#F56C6C',
        'PI文件': '#9C27B0',
        'PI': '#9C27B0'
      }

      return colorMap[stateStr] || '#909399'
    },

    // 获取状态文本
    getStateText(state) {
      // 如果state本身就是文本，直接返回
      if (typeof state === 'string' &&
          (state.includes('询价') ||
           state.includes('样品') ||
           state.includes('大货'))) {
        return state
      }

      // 确保状态值是字符串
      const stateStr = String(state)

      // 映射数字ID到名称
      const stateMap = {
        '1': '询价单&供应商确认',
        '2': '样品生产单',
        '3': '大货生产单',
        '4': 'PI文件'
      }

      // 尝试返回映射的值，如果不存在则返回未知状态
      return stateMap[stateStr] || `${stateStr}`
    },

    // 关闭抽屉
    close() {
      this.$emit('close')
    },

    // 类别名称建议搜索
    querySearchCategory(queryString, cb) {
      const categoryOptions = this.categoryOptions
      const results = queryString
        ? categoryOptions.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
        : categoryOptions

      // 返回建议列表
      cb(results)
    },

    // 选择建议项处理
    handleSelectCategory(item) {
      console.log('选中类别:', item)
    },

    // 处理粘贴事件
    handlePaste(event, category) {
      console.log('粘贴事件触发')
      const data = event.clipboardData || window.clipboardData
      if (data) {
        // 先检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('检测到图片URL:', textContent)
          // 直接添加URL到类别图片
          if (!category.images) {
            category.images = []
          }
          category.images.push(textContent)
          this.$message.success('图片URL已添加')

          // 如果类别已有ID且生产单已保存，自动保存类别
          if (category.id && this.productionOrderData.id) {
            console.log('类别已有ID，自动保存类别')
            this.handleSaveCategory(category)
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        console.log('剪贴板项目数量:', items.length)
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          console.log('项目类型:', items[i].kind, items[i].type)
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            console.log('获取到图片文件:', blob)
            this.handleImageUpload(blob, category)
            foundImage = true
          }
        }
        if (!foundImage) {
          this.$message.warning('未检测到图片，请确保复制的是图片内容或图片URL')
        }
      } else {
        this.$message.error('无法获取剪贴板数据')
      }
    },

    // 检查字符串是否是图片URL
    isImageUrl(str) {
      // 检查是否是URL格式
      try {
        const url = new URL(str)
        // 检查URL是否指向图片
        const pathLower = url.pathname.toLowerCase()
        const isImageExt =
          pathLower.endsWith('.jpg') ||
          pathLower.endsWith('.jpeg') ||
          pathLower.endsWith('.png') ||
          pathLower.endsWith('.gif') ||
          pathLower.endsWith('.webp') ||
          pathLower.endsWith('.svg') ||
          pathLower.endsWith('.bmp')
        return isImageExt || /\.(jpg|jpeg|png|gif|webp|svg|bmp)/i.test(url.search)
      } catch (e) {
        return false
      }
    },

    // 处理拖拽事件
    handleDrop(event, category) {
      event.preventDefault()
      const data = event.dataTransfer
      if (data) {
        // 检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('拖拽的图片URL:', textContent)
          // 直接添加URL到类别图片
          if (!category.images) {
            category.images = []
          }
          category.images.push(textContent)
          this.$message.success('图片URL已添加')

          // 如果类别已有ID且生产单已保存，自动保存类别
          if (category.id && this.productionOrderData.id) {
            console.log('类别已有ID，自动保存类别')
            this.handleSaveCategory(category)
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            this.handleImageUpload(blob, category)
            foundImage = true
          }
        }

        if (!foundImage) {
          // 尝试从dataTransfer.files获取文件
          const files = data.files
          for (let i = 0; i < files.length; i++) {
            if (files[i].type.indexOf('image/') !== -1) {
              this.handleImageUpload(files[i], category)
              foundImage = true
            }
          }
        }

        if (!foundImage) {
          this.$message.warning('未检测到图片文件')
        }
      }
    },

    // 处理图片上传
    handleImageUpload(blob, category) {
      if (!blob) {
        this.$message.error('图片文件无效')
        return
      }

      this.$message.info('正在处理图片...')
      const uploadId = `upload-${Date.now()}` // 创建唯一标识

      // 局部loading状态
      this.$set(category, 'imageLoading', true)

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const base64Data = e.target.result

          // 显示上传进度提示
          this.$notify({
            title: '上传中',
            message: '正在上传图片...',
            type: 'info',
            duration: 0,
            customClass: uploadId
          })

          // 调用上传接口
          UploadBase64Image({
            file_data: base64Data,
            directory_id: this.uploadDirectory || -1,
            keyword: this.uploadKeyword || ''
          })
            .then(response => {
              // 上传成功处理
              this.$notify.closeAll()
              this.$notify({
                title: '成功',
                message: '图片上传成功',
                type: 'success',
                duration: 2000
              })

              // 使用返回的URL更新类别图片
              if (!category.images) {
                category.images = []
              }
              category.images.push(response.data.url)

              // 如果类别已有ID且生产单已保存，自动保存类别
              if (category.id && this.productionOrderData.id) {
                console.log('类别已有ID，自动保存类别')
                this.handleSaveCategory(category)
              }

              // 关闭局部loading状态
              this.$set(category, 'imageLoading', false)
            })
            .catch(error => {
              // 上传失败处理
              this.$notify.closeAll()
              this.$notify({
                title: '错误',
                message: '图片上传失败: ' + (error.message || '未知错误'),
                type: 'error',
                duration: 3000
              })

              // 关闭局部loading状态
              this.$set(category, 'imageLoading', false)
            })
        } catch (err) {
          console.error('处理图片失败:', err)
          this.$message.error('图片处理失败')

          // 关闭局部loading状态
          this.$set(category, 'imageLoading', false)
        }
      }
      reader.onerror = () => {
        console.error('读取文件失败')
        this.$message.error('读取文件失败')

        // 关闭局部loading状态
        this.$set(category, 'imageLoading', false)
      }
      reader.readAsDataURL(blob)
    },

    // 触发文件输入
    triggerFileInput(category) {
      const input = this.$refs[`fileInput_${category.id || category.tempId}`][0]
      input.click()
    },

    // 处理文件变化
    handleFileChange(event, category) {
      const files = event.target.files
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        this.handleImageUpload(file, category)
      }
    },

    // 处理参数粘贴事件
    handleParameterPaste(event, parameter) {
      console.log('参数粘贴事件触发')
      const data = event.clipboardData || window.clipboardData
      if (data) {
        // 先检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('检测到参数图片URL:', textContent)
          // 直接添加URL到参数图片
          if (!parameter.images) {
            parameter.images = []
          }
          parameter.images.push(textContent)
          this.$message.success('参数图片URL已添加')

          // 如果参数已有ID，查找所属类别并自动保存参数
          if (parameter.id) {
            // 查找参数所属的类别
            const category = this.findCategoryByParameter(parameter)
            if (category && category.id && this.productionOrderData.id) {
              console.log('参数已有ID，自动保存参数')
              this.handleSaveParameter(category, parameter)
            }
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        console.log('剪贴板项目数量:', items.length)
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          console.log('项目类型:', items[i].kind, items[i].type)
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            console.log('获取到参数图片文件:', blob)
            this.handleParameterImageUpload(blob, parameter)
            foundImage = true
          }
        }
        if (!foundImage) {
          this.$message.warning('未检测到图片，请确保复制的是图片内容或图片URL')
        }
      } else {
        this.$message.error('无法获取剪贴板数据')
      }
    },

    // 处理参数拖拽事件
    handleParameterDrop(event, parameter) {
      event.preventDefault()
      const data = event.dataTransfer
      if (data) {
        // 检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('拖拽的参数图片URL:', textContent)
          // 直接添加URL到参数图片
          if (!parameter.images) {
            parameter.images = []
          }
          parameter.images.push(textContent)
          this.$message.success('参数图片URL已添加')

          // 如果参数已有ID，查找所属类别并自动保存参数
          if (parameter.id) {
            // 查找参数所属的类别
            const category = this.findCategoryByParameter(parameter)
            if (category && category.id && this.productionOrderData.id) {
              console.log('参数已有ID，自动保存参数')
              this.handleSaveParameter(category, parameter)
            }
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            this.handleParameterImageUpload(blob, parameter)
            foundImage = true
          }
        }

        if (!foundImage) {
          // 尝试从dataTransfer.files获取文件
          const files = data.files
          for (let i = 0; i < files.length; i++) {
            if (files[i].type.indexOf('image/') !== -1) {
              this.handleParameterImageUpload(files[i], parameter)
              foundImage = true
            }
          }
        }

        if (!foundImage) {
          this.$message.warning('未检测到图片文件')
        }
      }
    },

    // 处理参数图片上传
    handleParameterImageUpload(blob, parameter) {
      if (!blob) {
        this.$message.error('图片文件无效')
        return
      }

      this.$message.info('正在处理参数图片...')
      const uploadId = `upload-${Date.now()}` // 创建唯一标识

      // 局部loading状态
      this.$set(parameter, 'imageLoading', true)

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const base64Data = e.target.result

          // 显示上传进度提示
          this.$notify({
            title: '上传中',
            message: '正在上传参数图片...',
            type: 'info',
            duration: 0,
            customClass: uploadId
          })

          // 调用上传接口
          UploadBase64Image({
            file_data: base64Data,
            directory_id: this.uploadDirectory || -1,
            keyword: this.uploadKeyword || ''
          })
            .then(response => {
              // 上传成功处理
              this.$notify.closeAll()
              this.$notify({
                title: '成功',
                message: '参数图片上传成功',
                type: 'success',
                duration: 2000
              })

              // 使用返回的URL更新参数图片
              if (!parameter.images) {
                parameter.images = []
              }
              parameter.images.push(response.data.url)

              // 如果参数已有ID，查找所属类别并自动保存参数
              if (parameter.id) {
                // 查找参数所属的类别
                const category = this.findCategoryByParameter(parameter)
                if (category && category.id && this.productionOrderData.id) {
                  console.log('参数已有ID，自动保存参数')
                  this.handleSaveParameter(category, parameter)
                }
              }

              // 关闭局部loading状态
              this.$set(parameter, 'imageLoading', false)
            })
            .catch(error => {
              // 上传失败处理
              this.$notify.closeAll()
              this.$notify({
                title: '错误',
                message: '参数图片上传失败: ' + (error.message || '未知错误'),
                type: 'error',
                duration: 3000
              })

              // 关闭局部loading状态
              this.$set(parameter, 'imageLoading', false)
            })
        } catch (err) {
          console.error('处理参数图片失败:', err)
          this.$message.error('参数图片处理失败')

          // 关闭局部loading状态
          this.$set(parameter, 'imageLoading', false)
        }
      }
      reader.onerror = () => {
        console.error('读取参数文件失败')
        this.$message.error('读取参数文件失败')

        // 关闭局部loading状态
        this.$set(parameter, 'imageLoading', false)
      }
      reader.readAsDataURL(blob)
    },

    // 触发参数文件输入
    triggerParameterFileInput(parameter) {
      const input = this.$refs[`paramFileInput_${parameter.id || parameter.$index}`][0]
      input.click()
    },

    // 处理参数文件变化
    handleParameterFileChange(event, parameter) {
      const files = event.target.files
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        this.handleParameterImageUpload(file, parameter)
      }
    },

    // 获取焦点
    focusPasteArea(event) {
      event.preventDefault()
    },

    // 预览图片
    previewImage(imageUrl) {
      this.dialogImageUrl = imageUrl
      this.dialogImageVisible = true
    },

    // 移除类别图片
    removeCategoryImage(category, index) {
      if (category.images) {
        category.images.splice(index, 1)
      }
    },

    // 移除参数图片
    removeParameterImage(parameter, index) {
      if (parameter.images) {
        parameter.images.splice(index, 1)
      }
    },

    // 处理保存参数
    handleSaveParameter(category, parameter) {
      // 验证类别是否有id
      if (!category.id) {
        this.$message.warning('类别还未保存，请先保存生产单')
        return
      }

      this.parameterLoading = true

      // 确保图片数组存在并且是字符串格式
      const images = parameter.images || []

      // 构建要保存的参数数据
      const paramData = {
        name: parameter.name,
        value: parameter.value,
        color: parameter.color || '#000000',
        unit: parameter.unit || '',
        price: parameter.price || 0.0,
        crmproduction_order_category: category.id,
        images: images.join(',') // 将图片URL数组转换为逗号分隔的字符串
      }

      this.$message.info('正在保存参数...')

      // 根据是否有ID决定是创建还是更新
      if (parameter.id) {
        // 调用API更新参数
        PutParameter(parameter.id, paramData)
          .then(response => {
            console.log('参数更新成功:', response.data)
            this.$notify({
              title: '成功',
              message: '参数更新成功',
              type: 'success',
              duration: 2000
            })
            this.parameterLoading = false
          })
          .catch(error => {
            console.error('参数更新失败:', error)
            this.parameterLoading = false
            this.$notify.error({
              title: '错误',
              message: '参数更新失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      } else {
        // 调用API创建新参数
        PostParameter(paramData)
          .then(response => {
            console.log('新参数创建成功:', response.data)
            // 更新内存中的参数ID
            parameter.id = response.data.id
            this.$notify({
              title: '成功',
              message: '新参数创建成功',
              type: 'success',
              duration: 2000
            })
            this.parameterLoading = false
          })
          .catch(error => {
            console.error('新参数创建失败:', error)
            this.parameterLoading = false
            this.$notify.error({
              title: '错误',
              message: '新参数创建失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      }
    },

    // 处理保存类别
    handleSaveCategory(category) {
      // 验证生产单是否有id
      if (!this.productionOrderData.id) {
        this.$message.warning('生产单还未保存，请先保存生产单')
        return
      }

      this.categoryLoading = true

      // 确保图片数组存在并且是字符串格式
      const images = category.images || []

      // 构建要保存的类别数据
      const categoryData = {
        name: category.name,
        production_order: this.productionOrderData.id,
        images: images.join(','), // 将图片URL数组转换为逗号分隔的字符串
        position: category.position || 0, // 确保包含position字段
        is_shown: category.is_shown === undefined ? true : category.is_shown // 确保包含is_shown字段
      }

      this.$message.info('正在保存类别...')

      // 根据是否有ID决定是创建还是更新
      if (category.id) {
        // 调用API更新类别
        PutCategory(category.id, categoryData)
          .then(response => {
            console.log('类别更新成功:', response.data)
            this.$notify({
              title: '成功',
              message: '类别更新成功',
              type: 'success',
              duration: 2000
            })
            this.categoryLoading = false
          })
          .catch(error => {
            console.error('类别更新失败:', error)
            this.categoryLoading = false
            this.$notify.error({
              title: '错误',
              message: '类别更新失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      } else {
        // 调用API创建新类别
        PostCategory(categoryData)
          .then(response => {
            console.log('新类别创建成功:', response.data)
            // 更新内存中的类别ID
            category.id = response.data.id
            // 更新tempId
            delete category.tempId
            this.$notify({
              title: '成功',
              message: '新类别创建成功',
              type: 'success',
              duration: 2000
            })
            this.categoryLoading = false
          })
          .catch(error => {
            console.error('新类别创建失败:', error)
            this.categoryLoading = false
            this.$notify.error({
              title: '错误',
              message: '新类别创建失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      }
    },

    // 查找参数所属的类别
    findCategoryByParameter(parameter) {
      if (!this.productionOrderData.categories) {
        return null
      }

      for (const category of this.productionOrderData.categories) {
        if (!category.parameters) {
          continue
        }

        const found = category.parameters.find(p => p === parameter || p.id === parameter.id)
        if (found) {
          return category
        }
      }

      return null
    },
    openExternalLink() {
      // 所有类型都使用po.lianf.com域名
      const url = `https://po.lianf.com/${this.productionOrderData.token}`
      window.open(url, '_blank')
    },
    handleGetDefaultParams() {
      GetDefaultParams()
        .then(response => {
          if (response.categoryOptions && response.categoryOptions.length) {
            this.categoryOptions = response.categoryOptions
          }
          if (response.paramsOptions && response.paramsOptions.length) {
            this.paramsOptions = response.paramsOptions
          }
        })
    },
    // 处理类别重新排序
    handleCategoryReorder() {
      // 更新所有类别的position值
      this.productionOrderData.categories.forEach((category, index) => {
        category.position = index + 1
      })

      this.$message.success('类别顺序已更新，请保存以应用更改')

      // 如果生产单已有ID，自动保存所有类别的排序
      if (this.productionOrderData.id) {
        this.saveAllCategoriesPosition()
      }
    },

    // 保存所有类别的排序
    saveAllCategoriesPosition() {
      if (!this.productionOrderData.id) {
        this.$message.warning('请先保存生产单')
        return
      }

      const promises = []
      this.loading = true

      this.productionOrderData.categories.forEach(category => {
        if (category.id) {
          // 只更新position字段
          const updateData = {
            position: category.position
          }

          promises.push(
            PutCategory(category.id, updateData)
              .catch(error => {
                console.error(`更新类别 ${category.name} 排序失败:`, error)
                return Promise.reject(error)
              })
          )
        }
      })

      Promise.all(promises)
        .then(() => {
          this.$notify({
            title: '成功',
            message: '类别排序已保存',
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
        .catch(error => {
          this.$notify.error({
            title: '错误',
            message: '保存类别排序失败: ' + (error.message || '未知错误'),
            duration: 3000
          })
          this.loading = false
        })
    },

    // 打开Markdown编辑器
    openMarkdownEditor(parameter) {
      this.currentEditingParameter = parameter
      this.currentMarkdownContent = parameter.value || ''
      this.markdownDialogVisible = true
    },

    // 关闭Markdown编辑器
    closeMarkdownDialog() {
      this.markdownDialogVisible = false
      this.currentEditingParameter = null
    },

    // 确认Markdown编辑
    confirmMarkdownEdit() {
      if (this.currentEditingParameter) {
        this.currentEditingParameter.value = this.currentMarkdownContent

        // 如果参数已有ID且生产单已保存，自动保存参数
        if (this.currentEditingParameter.id) {
          // 查找参数所属的类别
          const category = this.findCategoryByParameter(this.currentEditingParameter)
          if (category && category.id && this.productionOrderData.id) {
            this.handleSaveParameter(category, this.currentEditingParameter)
          }
        }
      }
      this.closeMarkdownDialog()
    },
    isMarkdown(text) {
      if (!text) return false
      // 提高判断准确性，扩展检测更多Markdown特性
      return text.includes('#') ||
             text.includes('- ') ||
             text.includes('* ') ||
             text.includes('```') ||
             text.includes('> ') ||
             text.includes('|---|') ||
             text.includes('![') ||
             text.includes('[') ||
             /\[(.*?)\]\((.*?)\)/.test(text) || // 检测链接格式
             /^```[\s\S]*?```$/m.test(text) // 检测代码块
    },
    // 在methods部分添加处理参数值变化的方法
    handleParamValueChange(parameter) {
      // 如果参数已有ID，查找所属类别并自动保存参数
      if (parameter.id && this.productionOrderData.id) {
        // 查找参数所属的类别
        const category = this.findCategoryByParameter(parameter)
        if (category && category.id) {
          // 为避免频繁保存，这里可以考虑使用节流或防抖
          // 简单实现：延迟1秒后保存
          if (this.saveParamTimeout) {
            clearTimeout(this.saveParamTimeout)
          }
          this.saveParamTimeout = setTimeout(() => {
            this.handleSaveParameter(category, parameter)
          }, 1000)
        }
      }
    },
    showVersionsDialog() {
      this.versionsDialogVisible = true
      // 使用现有的生产单数据，不需要重新获取
      if (this.allProductionOrders.length <= 1) {
        // 如果当前只有一个或没有生产单，尝试再次获取
        this.getAllProductionOrders()
      }
    },
    switchToVersion(version) {
      this.loading = true

      // 获取完整的生产单数据
      Get(version.id).then(response => {
        if (response.data) {
          // 临时存储数据，使用深拷贝避免引用问题
          const tempData = JSON.parse(JSON.stringify(response.data))
          this.title = `生产单详情: ${tempData.name || '未命名'}`

          // 确保categories存在且是数组
          if (!tempData.categories) {
            tempData.categories = []
          }

          // 处理类别和参数中的图片字符串，将其转换为数组
          tempData.categories.forEach(category => {
            // 处理类别图片
            if (category.images && typeof category.images === 'string') {
              category.images = category.images.split(',').filter(url => url.trim() !== '')
            } else if (!category.images) {
              category.images = []
            }

            // 处理参数图片
            if (category.parameters && Array.isArray(category.parameters)) {
              category.parameters.forEach(param => {
                if (param.images && typeof param.images === 'string') {
                  param.images = param.images.split(',').filter(url => url.trim() !== '')
                } else if (!param.images) {
                  param.images = []
                }
              })
            }
          })

          // 完全替换数据，触发响应式更新
          this.productionOrderData = tempData

          this.$nextTick(() => {
            // 设置初始展开的面板
            this.activeCollapse = tempData.categories.map(cat => cat.id || cat.tempId)
            // 刷新图片显示
            this.refreshImages()
          })

          this.$notify({
            title: '成功',
            message: `已切换到生产单: ${tempData.name || '未命名'}`,
            type: 'success',
            duration: 2000
          })
        }

        this.loading = false
        this.versionsDialogVisible = false
      }).catch(error => {
        console.error('加载生产单版本失败', error)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '加载生产单版本失败: ' + (error.message || '未知错误')
        })
      })
    },
    handleOrderCommand(command) {
      if (command === 'copy') {
        this.copyProductionOrder()
      } else if (command === 'new') {
        this.createNewProductionOrder()
      }
    },
    // 复制当前生产单
    copyProductionOrder() {
      if (!this.productionOrderData.id) {
        this.$message.warning('请先保存当前生产单再进行复制')
        return
      }

      this.loading = true
      this.$message({
        message: '正在复制生产单，请稍候...',
        type: 'info',
        duration: 0,
        showClose: true
      })

      // 获取完整的当前生产单数据（包括完整的类别和参数）
      Get(this.productionOrderData.id).then(response => {
        if (!response.data) {
          this.$message.error('获取生产单详情失败')
          this.loading = false
          return
        }

        // 复制当前生产单数据，但删除id和token等唯一标识
        const copyData = JSON.parse(JSON.stringify(response.data))
        delete copyData.id
        delete copyData.token

        // 修改名称，添加复制标记和时间戳
        const now = new Date()
        const timeStr = now.getFullYear() +
                      ('0' + (now.getMonth() + 1)).slice(-2) +
                      ('0' + now.getDate()).slice(-2) +
                      ('0' + now.getHours()).slice(-2) +
                      ('0' + now.getMinutes()).slice(-2)
        copyData.name = `${copyData.name || '未命名'}-复制-${timeStr}`

        // 处理类别和参数，删除它们的ID以便创建新记录
        if (copyData.categories && copyData.categories.length > 0) {
          copyData.categories = copyData.categories.map(category => {
            // 保留图片数据
            let images = category.images
            if (typeof images === 'string') {
              images = images.split(',').filter(url => url.trim() !== '')
            }

            // 构建新的类别对象，不包含ID
            const newCategory = {
              name: category.name,
              position: category.position,
              images: Array.isArray(images) ? images.join(',') : ''
            }

            // 处理参数，删除参数ID
            if (category.parameters && category.parameters.length > 0) {
              newCategory.parameters = category.parameters.map(param => {
                // 保留图片数据
                let paramImages = param.images
                if (typeof paramImages === 'string') {
                  paramImages = paramImages.split(',').filter(url => url.trim() !== '')
                }

                // 构建新的参数对象，不包含ID
                return {
                  name: param.name,
                  value: param.value,
                  color: param.color || '#000000',
                  unit: param.unit || '',
                  price: param.price || 0.0,
                  images: Array.isArray(paramImages) ? paramImages.join(',') : ''
                }
              })
            }

            return newCategory
          })
        }

        // 调用API创建新的生产单
        Post(copyData).then(response => {
          const newProductionOrder = response.data.data

          // 关闭之前的提示
          this.$message.closeAll()

          this.$notify({
            title: '成功',
            message: '生产单复制成功',
            type: 'success',
            duration: 2000
          })

          // 重新获取所有生产单数据
          this.getAllProductionOrders()

          // 重新加载新生产单的完整数据
          this.reloadProductionOrderData(newProductionOrder.id)
        }).catch(error => {
          console.error('复制生产单失败', error)
          this.loading = false
          this.$notify.error({
            title: '错误',
            message: '复制生产单失败: ' + (error.message || '未知错误')
          })
        })
      }).catch(error => {
        console.error('获取生产单详情失败', error)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '获取生产单详情失败: ' + (error.message || '未知错误')
        })
      })
    },

    // 创建全新生产单
    createNewProductionOrder() {
      // 确认对话框
      this.$confirm('确定要创建新的生产单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置生产单数据
        this.productionOrderData = {
          name: this.order_no ? `${this.order_no}+生产需求单` : '',
          state: '1',
          crm_order_no: this.order_no,
          contact_phone: '',
          contact_name: '',
          categories: [],
          // PI相关字段
          currency: 'USD',
          order_amount: 'USD:100',
          invoice_number: '',
          pi_address: '',
          pi_email: '',
          pi_phone: '',
          pi_website: '',
          pi_account_holder_name: '',
          pi_account_number: '',
          pi_bank_name: '',
          pi_bak_address: '',
          pi_ach_routing_number: '',
          pi_wire_transfer_number: '',
          pi_swift_code: '',
          pi_company_name: '',
          company_logo: ''
        }

        this.title = '新建生产单'

        // 尝试从cookies恢复用户数据
        this.restoreFromCookies()

        // 清除当前生产单ID，表示这是一个新的生产单
        this.$nextTick(() => {
          // 创建一个默认的空类别
          this.handleAddCategory()

          this.$notify({
            title: '成功',
            message: '已创建新的生产单，请填写信息并保存',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        // 取消操作
      })
    },
    // 获取所有生产单版本
    getAllProductionOrders() {
      this.versionsLoading = true

      Get(null, qs.stringify({ order_no: this.order_no })).then(response => {
        if (response.data && response.data.data && response.data.data.length > 0) {
          this.allProductionOrders = [...response.data.data]

          // 按创建时间降序排序，确保最新的在前面
          this.allProductionOrders.sort((a, b) => {
            return new Date(b.create_at) - new Date(a.create_at)
          })
        } else {
          this.allProductionOrders = []
          this.$message.info('未找到关联的生产单')
        }
        this.versionsLoading = false
      }).catch(error => {
        console.error('获取生产单版本列表失败', error)
        this.versionsLoading = false
        this.$notify.error({
          title: '错误',
          message: '获取生产单版本列表失败: ' + (error.message || '未知错误')
        })
      })
    },
    handleVersionSearch() {
      // 不需要执行特定的搜索操作，filteredProductionOrders计算属性会自动处理
      console.log('搜索条件变更:', this.versionSearchKeyword, '状态:', this.versionFilterState, '排序:', this.versionSortOrder)
    },
    // 打开特定版本的外部链接
    openVersionExternalLink(version) {
      if (!version.token) {
        this.$message.warning('此生产单尚未生成链接')
        return
      }
      const url = `https://po.lianf.com/${version.token}`
      window.open(url, '_blank')
    },

    // 处理删除版本
    handleDeleteVersion(version) {
      if (this.allProductionOrders.length <= 1) {
        this.$message.warning('不能删除唯一的生产单版本')
        return
      }

      // 确认删除
      this.$confirm(`确定要删除生产单 "${version.name || '未命名'}"?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteProductionOrder(version)
      }).catch(() => {
        // 取消删除
      })
    },

    // 删除生产单
    deleteProductionOrder(version) {
      this.versionsLoading = true

      // 调用删除API
      Delete(version.id).then(() => {
        this.$notify({
          title: '成功',
          message: '生产单删除成功',
          type: 'success',
          duration: 2000
        })

        // 如果删除的是当前显示的生产单，需要切换到其他版本
        if (version.id === this.productionOrderData.id) {
          // 从列表中移除已删除的版本
          this.allProductionOrders = this.allProductionOrders.filter(po => po.id !== version.id)

          // 如果还有其他版本，则切换到最新的一个
          if (this.allProductionOrders.length > 0) {
            this.switchToVersion(this.allProductionOrders[0])
          } else {
            // 如果没有其他版本，创建新的空白生产单
            this.createNewProductionOrder()
            this.versionsDialogVisible = false
          }
        } else {
          // 从列表中移除已删除的版本
          this.allProductionOrders = this.allProductionOrders.filter(po => po.id !== version.id)
          this.versionsLoading = false
        }
      }).catch(error => {
        console.error('删除生产单失败', error)
        this.versionsLoading = false
        this.$notify.error({
          title: '错误',
          message: '删除生产单失败: ' + (error.message || '未知错误')
        })
      })
    },
    // 处理AI分析结果应用
    handleApplyAIResult(result, category) {
      if (!result) return

      try {
        // 创建一个新的参数来存储AI分析结果
        if (!category.parameters) {
          category.parameters = []
        }

        // 添加一个新参数用于存储分析结果
        category.parameters.push({
          name: '参数要点',
          value: result,
          color: '#000000',
          crmproduction_order_category: category.id,
          images: []
        })

        // 如果类别已有ID，自动保存新参数
        if (category.id && this.productionOrderData.id) {
          // 找到新添加的参数
          const newParam = category.parameters[category.parameters.length - 1]
          this.handleSaveParameter(category, newParam)
        }

        this.$notify({
          title: '成功',
          message: 'AI分析结果已添加为新参数',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        console.error('应用AI分析结果失败', error)
        this.$notify.error({
          title: '错误',
          message: '应用AI分析结果失败'
        })
      }
    },
    // 处理类别可见性变更
    handleCategoryVisibilityChange(category) {
      // 如果类别已有ID且生产单已保存，自动保存类别
      if (category.id && this.productionOrderData.id) {
        this.handleSaveCategory(category)

        // 显示状态变更提示
        const statusText = category.is_shown ? '显示' : '隐藏'
        this.$message({
          message: `类别"${category.name}"已设置为${statusText}`,
          type: 'success',
          duration: 1500
        })
      }
    },
    // 处理AI分析结果应用
    handleApplyParameterAIResult(result, parameter) {
      if (!result) return

      try {
        // 将AI分析结果设置为参数的值
        parameter.value = result

        // 如果参数已有ID，自动保存参数
        if (parameter.id) {
          // 查找参数所属的类别
          const category = this.findCategoryByParameter(parameter)
          if (category && category.id && this.productionOrderData.id) {
            this.handleSaveParameter(category, parameter)
          }
        }

        this.$notify({
          title: '成功',
          message: 'AI分析结果已应用到参数',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        console.error('应用AI分析结果失败', error)
        this.$notify.error({
          title: '错误',
          message: '应用AI分析结果失败'
        })
      }
    },
    showSelectPIAccount() {
      // 实现选择PI账户的逻辑
      console.log('选择PI账户')
      this.piSelectVisible = true
    },
    showManagePIAccount() {
      // 实现管理PI账户的逻辑
      console.log('管理PI账户')
      this.piManageVisible = true
    },
    handlePIAccountSelect(account) {
      // 处理PI账户选择的逻辑
      console.log('选择的PI账户:', account)

      // 复制PI账户信息到生产单
      this.productionOrderData.pi_company_name = account.pi_company_name || ''
      this.productionOrderData.pi_email = account.pi_email || ''
      this.productionOrderData.pi_phone = account.pi_phone || ''
      this.productionOrderData.pi_website = account.pi_website || ''
      this.productionOrderData.pi_address = account.pi_address || ''
      this.productionOrderData.pi_account_holder_name = account.pi_account_holder_name || ''
      this.productionOrderData.pi_account_number = account.pi_account_number || ''
      this.productionOrderData.pi_bank_name = account.pi_bank_name || ''
      this.productionOrderData.pi_bak_address = account.pi_bak_address || ''
      this.productionOrderData.pi_ach_routing_number = account.pi_ach_routing_number || ''
      this.productionOrderData.pi_wire_transfer_number = account.pi_wire_transfer_number || ''
      this.productionOrderData.pi_swift_code = account.pi_swift_code || ''
      this.productionOrderData.company_logo = account.company_logo || ''

      // 显示成功提示
      this.$notify({
        title: '成功',
        message: `已应用PI账户信息：${account.name}`,
        type: 'success',
        duration: 2000
      })

      // 保存到cookies
      this.saveToCookies()
    },
    handleLogoError() {
      console.error('公司Logo加载失败')
      this.$message.error('公司Logo加载失败')
    },
    previewLogo() {
      this.dialogImageUrl = this.productionOrderData.company_logo
      this.dialogImageVisible = true
    },
    clearLogo() {
      this.productionOrderData.company_logo = ''
      this.$message.success('公司Logo已清除')
    }
  }
}
</script>

<style scoped>
.el-collapse {
  margin-top: 20px;
}
/* 针对自定义类名的样式规则 */
.small-upload ::v-deep .el-upload--picture-card {
  width: 40px !important;
  height: 40px !important;
  line-height: 40px !important;
  font-size: 20px !important;
}
.el-upload--picture-card {
  width: 40px !important;
  height: 40px !important;
  line-height: 40px !important;
}
.form-item {
  margin-bottom: 15px;
}
.form-label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}
.el-collapse-item >>> .el-collapse-item__header {
  background-color: #f0f9ff;
  padding: 12px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 16px;
  border-left: 4px solid #409EFF;
  display: flex;
  align-items: center;
}
.el-collapse-item >>> .el-collapse-item__content {
  padding: 15px;
  background-color: #f7fbff;
  border: 1px solid #ebeef5;
  border-radius: 0 0 4px 4px;
  margin-bottom: 10px;
}

/* 类别区域样式 */
.category-container {
  background-color: #f0f9ff;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  border: 1px solid #d1e9ff;
}

/* 参数表格样式 */
.parameters-table {
  background-color: #ffffff;
  border-radius: 4px;
  margin-top: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.parameters-table >>> .el-table__header-wrapper {
  background-color: #f5f7fa;
}

.parameters-table >>> .el-table th {
  background-color: #f5f7fa;
}

.parameters-table >>> .el-table--border {
  border: 1px solid #ebeef5;
}

/* 底部添加按钮样式 */
.bottom-add-button {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.bottom-add-button .el-button {
  padding: 8px 20px;
}

.bottom-add-category {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}

.upload-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}
.paste-area {
  padding: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  text-align: center;
  margin-bottom: 10px;
  cursor: pointer;
  background-color: #fafafa;
  transition: all 0.3s;
  min-height: 100px;
  outline: none;
}
.paste-area:hover, .paste-area:focus {
  border-color: #409EFF;
  background-color: #f5f7fa;
}
.paste-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 80px;
}
.paste-tip i {
  font-size: 24px;
  color: #909399;
  margin-bottom: 5px;
}
.parameter-paste-area {
  min-height: 50px;
  display: flex;
  flex-direction: column;
}
.parameter-paste-area .paste-tip {
  flex-direction: row;
  justify-content: center;
}
.parameter-paste-area .paste-tip i {
  font-size: 16px;
  margin-right: 5px;
  margin-bottom: 0;
}
.paste-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 5px;
}
.image-item {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}
.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.delete-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  padding: 3px;
  color: #F56C6C;
  cursor: pointer;
}
.delete-icon:hover {
  background-color: rgba(255, 255, 255, 1);
  transform: scale(1.1);
}
.parameter-images {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.parameter-image-item {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

/* 优化表单样式 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item >>> .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-form-item >>> .el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s;
}

.el-form-item >>> .el-input__inner:hover {
  border-color: #c0c4cc;
}

.el-form-item >>> .el-input__inner:focus {
  border-color: #409EFF;
}

/* 分隔线样式 */
.el-divider {
  margin: 24px 0;
}

.el-divider >>> .el-divider__text {
  background-color: #f5f7fa;
  color: #409EFF;
  font-weight: bold;
  padding: 0 20px;
}

/* 抽屉内容区域样式 */
.production-order-drawer ::v-deep .el-drawer__wrapper {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  overflow: hidden !important;
}

.production-order-drawer ::v-deep .el-drawer {
  display: flex !important;
  flex-direction: column !important;
  height: 100% !important;
}

.production-order-drawer ::v-deep .el-drawer__header {
  margin-bottom: 0 !important;
  padding: 15px 20px !important;
  border-bottom: 1px solid #ebeef5 !important;
  background-color: #f5f7fa !important;
  flex-shrink: 0 !important;
}

.production-order-drawer ::v-deep .el-drawer__body {
  padding: 0 !important;
  flex: 1 !important;
  overflow-y: auto !important;
  overflow-x: hidden !important;
  height: auto !important;
  max-height: none !important;
}

/* 新添加的样式 */
.drawer-content {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  box-sizing: border-box;
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
}

.order-title {
  display: inline-block;
  font-size: 20px;
  font-weight: 600;
  margin-right: 10px;
  color: #303133;
}

.order-info {
  display: block;
  margin-top: 8px;
  color: #606266;
  font-size: 14px;
}

.info-item {
  margin-right: 15px;
}

.action-buttons {
  text-align: right;
  padding-top: 5px;
}

@media (max-width: 992px) {
  .action-buttons {
    text-align: left;
    margin-top: 15px;
  }
}

/* 美化表单样式 */
.el-form {
  background-color: #f9fafc;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 按钮样式优化 */
.el-button {
  margin-left: 10px;
}

.el-button:first-child {
  margin-left: 0;
}

/* 抽屉全局样式 */
.production-order-drawer >>> .el-drawer__header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

/* 类别拖拽样式 */
.category-drag-handle {
  cursor: move;
  margin-right: 8px;
  color: #909399;
}

.category-drag-handle:hover {
  color: #409EFF;
}

.category-position {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

/* Markdown编辑器相关样式 */
.markdown-input-container {
  position: relative;
}

.markdown-icon {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 18px;
  color: #409EFF;
  cursor: pointer;
  z-index: 1;
  padding: 4px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s;
}

.markdown-icon:hover {
  color: #66b1ff;
  background-color: rgba(240, 240, 240, 0.9);
  transform: scale(1.1);
}

/* 自定义v-md-editor样式 */
::v-deep .v-md-editor {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
}

::v-deep .v-md-editor__toolbar {
  border-bottom: 1px solid #DCDFE6;
}

/* Markdown对话框样式 */
.markdown-dialog {
  margin-top: 5vh !important;
}

::v-deep .markdown-dialog .el-dialog__body {
  padding: 10px 20px;
}

::v-deep .markdown-dialog .v-md-editor {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.markdown-preview-container {
  position: relative;
  width: 100%;
  margin-bottom: 10px;
}

/* Markdown预览样式 */
.markdown-preview-container ::v-deep .v-md-editor {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.markdown-preview-container ::v-deep .v-md-editor__preview-wrapper {
  padding: 10px 15px;
  background-color: #ffffff;
}

.markdown-preview-container ::v-deep .v-md-editor__preview p {
  margin: 8px 0;
}

.markdown-preview-container ::v-deep .v-md-editor__preview h1,
.markdown-preview-container ::v-deep .v-md-editor__preview h2,
.markdown-preview-container ::v-deep .v-md-editor__preview h3 {
  margin-top: 12px;
  margin-bottom: 8px;
  color: #303133;
}

.markdown-preview-container ::v-deep .v-md-editor__preview ul,
.markdown-preview-container ::v-deep .v-md-editor__preview ol {
  padding-left: 20px;
}

.markdown-preview-container ::v-deep .v-md-editor__preview code {
  background-color: #f5f7fa;
  padding: 2px 4px;
  border-radius: 3px;
  color: #E6A23C;
}

.markdown-preview-container ::v-deep .v-md-editor__preview pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin: 10px 0;
}

/* 确保编辑图标在预览模式下始终可见 */
.markdown-preview-container .markdown-icon {
  position: absolute;
  right: 10px;
  top: 10px;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 图片AI按钮样式 */
.image-ai-button {
  position: absolute;
  bottom: 5px;
  right: 5px;
  z-index: 5;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 3px;
}

/* 参数图片AI按钮样式 */
.parameter-image-item .image-ai-button {
  bottom: 3px;
  right: 3px;
  padding: 1px;
  transform: scale(0.8);
}

.parameter-image-item .image-ai-button ::v-deep .el-button--mini {
  padding: 4px 6px;
  font-size: 10px;
}

/* 版本对话框样式 */
.version-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.version-current-tag {
  background-color: #67C23A;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  margin-left: 5px;
}

.token-link {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
}

.token-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.token-time {
  font-size: 12px;
  color: #909399;
  margin-top: 3px;
}

.el-dropdown {
  display: inline-block;
}

/* 在小屏幕下优化下拉菜单显示 */
@media (max-width: 768px) {
  .el-dropdown {
    display: block;
    margin-top: 10px;
  }
}

.logo-input-container {
  display: flex;
  flex-direction: column;
}

.logo-preview {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.logo-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logo-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.clear-logo-btn {
  color: #f56c6c;
}
</style>

